<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="产品名称" prop="productId">
<!--        <el-autocomplete-->
<!--            v-model="queryParams.productId"-->
<!--            :fetch-suggestions="loadProductList"-->
<!--            placeholder="请输入产品名称"-->
<!--            clearable-->
<!--            @keyup.enter="handleQuery"-->
<!--            @select="handleSelect"-->
<!--        />-->
        <el-select
            v-model="queryParams.productId"
            placeholder="请选择产品名称"
            clearable
            filterable
            style="width: 180px"
        >
          <el-option
            v-for="item in productList"
            :key="item.productId"
            :label="item.name"
            :value="item.productId"
          >
          </el-option>
        </el-select>
      </el-form-item>
<!--      <el-form-item label="当前库存量" prop="currentQuantity">-->
<!--        <el-input-->
<!--          v-model="queryParams.currentQuantity"-->
<!--          placeholder="请输入当前库存量"-->
<!--          clearable-->
<!--          @keyup.enter="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="锁定库存量" prop="lockedQuantity">-->
<!--        <el-input-->
<!--          v-model="queryParams.lockedQuantity"-->
<!--          placeholder="请输入锁定库存量"-->
<!--          clearable-->
<!--          @keyup.enter="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="可用库存量" prop="availableQuantity">-->
<!--        <el-input-->
<!--          v-model="queryParams.availableQuantity"-->
<!--          placeholder="请输入可用库存量"-->
<!--          clearable-->
<!--          @keyup.enter="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="创建人" prop="createdBy">-->
<!--        <el-input-->
<!--          v-model="queryParams.createdBy"-->
<!--          placeholder="请输入创建人"-->
<!--          clearable-->
<!--          @keyup.enter="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="创建时间" style="width: 308px">-->
<!--        <el-date-picker-->
<!--          v-model="daterangeCreatedAt"-->
<!--          value-format="YYYY-MM-DD"-->
<!--          type="daterange"-->
<!--          range-separator="-"-->
<!--          start-placeholder="开始日期"-->
<!--          end-placeholder="结束日期"-->
<!--        ></el-date-picker>-->
<!--      </el-form-item>-->
<!--      <el-form-item label="修改人" prop="updatedBy">-->
<!--        <el-input-->
<!--          v-model="queryParams.updatedBy"-->
<!--          placeholder="请输入修改人"-->
<!--          clearable-->
<!--          @keyup.enter="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="修改时间" style="width: 308px">-->
<!--        <el-date-picker-->
<!--          v-model="daterangeUpdatedAt"-->
<!--          value-format="YYYY-MM-DD"-->
<!--          type="daterange"-->
<!--          range-separator="-"-->
<!--          start-placeholder="开始日期"-->
<!--          end-placeholder="结束日期"-->
<!--        ></el-date-picker>-->
<!--      </el-form-item>-->
<!--      <el-form-item label="库存记录最后修改时间" style="width: 308px">-->
<!--        <el-date-picker-->
<!--          v-model="daterangeLastUpdated"-->
<!--          value-format="YYYY-MM-DD"-->
<!--          type="daterange"-->
<!--          range-separator="-"-->
<!--          start-placeholder="开始日期"-->
<!--          end-placeholder="结束日期"-->
<!--        ></el-date-picker>-->
<!--      </el-form-item>-->
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['SysSales:SysSalesInventory:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['SysSales:SysSalesInventory:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['SysSales:SysSalesInventory:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['SysSales:SysSalesInventory:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="SysSalesInventoryList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="inventoryId" :show-overflow-tooltip="true"/>
      <el-table-column label="产品名称" align="center" prop="name" :show-overflow-tooltip="true"/>
      <el-table-column label="当前库存量" align="center" prop="currentQuantity" :show-overflow-tooltip="true"/>
      <el-table-column label="锁定库存量" align="center" prop="lockedQuantity" :show-overflow-tooltip="true"/>
      <el-table-column label="可用库存量" align="center" prop="availableQuantity" />
<!--      <el-table-column label="创建人" align="center" prop="createdBy" />-->
<!--      <el-table-column label="创建时间" align="center" prop="createdAt" width="180">-->
<!--        <template #default="scope">-->
<!--          <span>{{ parseTime(scope.row.createdAt, '{y}-{m}-{d}') }}</span>-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--      <el-table-column label="修改人" align="center" prop="updatedBy" />-->
<!--      <el-table-column label="修改时间" align="center" prop="updatedAt" width="180">-->
<!--        <template #default="scope">-->
<!--          <span>{{ parseTime(scope.row.updatedAt, '{y}-{m}-{d}') }}</span>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column label="库存记录最后修改时间" align="center" prop="lastUpdated" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.lastUpdated, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['SysSales:SysSalesInventory:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['SysSales:SysSalesInventory:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改产品库存对话框 -->
    <el-dialog :title="title" v-model="open" width="400px" append-to-body>
      <el-form ref="SysSalesInventoryRef" :model="form" :rules="rules" label-width="80px" style="margin-left: 5px">
        <el-form-item label="产品名称" prop="productId">
<!--          <el-select v-model="form.productId" placeholder="请选择产品名称">-->
<!--            <el-option-->
<!--              v-for="item in productList"-->
<!--              :key="item.productId"-->
<!--              :label="item.name"-->
<!--              :value="item.productId"-->
<!--            />-->
<!--          </el-select>-->
          <el-select
              v-model="form.productId"
              placeholder="请选择产品名称"
              clearable
              filterable
              style="width: 300px"
          >
            <el-option
                v-for="item in productList"
                :key="item.productId"
                :label="item.name"
                :value="item.productId"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="当前库存量" prop="currentQuantity" label-width="92px" style="margin-left: -11px">
          <el-input v-model="form.currentQuantity" placeholder="请输入当前库存量" />
        </el-form-item>
        <el-form-item label="锁定库存量" prop="lockedQuantity" label-width="92px" style="margin-left: -11px">
          <el-input v-model="form.lockedQuantity" placeholder="请输入锁定库存量" />
        </el-form-item>
<!--        <el-form-item label="可用库存量" prop="availableQuantity">-->
<!--          <el-input v-model="form.availableQuantity" placeholder="请输入可用库存量" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="库存记录最后修改时间" prop="lastUpdated">-->
<!--          <el-date-picker clearable-->
<!--            v-model="form.lastUpdated"-->
<!--            type="date"-->
<!--            value-format="YYYY-MM-DD"-->
<!--            placeholder="请选择库存记录最后修改时间">-->
<!--          </el-date-picker>-->
<!--        </el-form-item>-->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="SysSalesInventory">
import { listSysSalesInventory, getSysSalesInventory, delSysSalesInventory, addSysSalesInventory, updateSysSalesInventory } from "@/api/SysSales/SysSalesInventory"
import { listSysSalesProducts } from "@/api/SysSales/SysSalesProducts"
import {onMounted} from "vue";

const { proxy } = getCurrentInstance()

const SysSalesInventoryList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const productList = ref([])
const daterangeCreatedAt = ref([])
const daterangeUpdatedAt = ref([])
const daterangeLastUpdated = ref([])

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: null,
    productId: null,
    currentQuantity: null,
    lockedQuantity: null,
    availableQuantity: null,
    createdBy: null,
    createdAt: null,
    updatedBy: null,
    updatedAt: null,
    lastUpdated: null
  },
  rules: {
    productId: [
      { required: true, message: "产品名称不能为空", trigger: "blur" }
    ],
    currentQuantity: [
      { required: true, message: "当前库存量不能为空", trigger: "blur" }
    ],
    lockedQuantity: [
      { required: true, message: "锁定库存量不能为空", trigger: "blur" },
      { validator: validateLockedQuantity, trigger: "blur" }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)

onMounted(() => {
  getProductOptions()
})
/** 锁定库存量校验方法 */
// 添加自定义校验函数
function validateLockedQuantity(rule, value, callback) {
  if (value === null || value === undefined) {
    callback(new Error('锁定库存量不能为空'))
    return
  }

  // 确保 currentQuantity 是数字类型
  const currentQuantity = Number(form.value.currentQuantity)

  // 检查 currentQuantity 是否有效
  if (isNaN(currentQuantity)) {
    callback(new Error('当前库存量格式不正确'))
    return
  }

  // 比较锁定库存量是否大于当前库存量
  if (value > currentQuantity) {
    callback(new Error('锁定库存量不能大于当前库存量'))
    return
  }

  callback()
}
/** 查询产品列表 */
function getProductOptions(){
  listSysSalesProducts({ pageNum: 1, pageSize: 1000 }).then(res => {
    productList.value = res.rows
    console.log(res)
  })
}
// function loadProductList(query) {
//   return new Promise((resolve) => {
//     listSysSalesProducts({}).then(response => {
//       const products = response.rows.map(item => ({
//         value: item.productId,
//         label: item.name
//       }))
//       resolve(products)
//     })
//   })
// }

/** 查询产品库存列表 */
function getList() {
  loading.value = true
  queryParams.value.params = {}
  if (null != daterangeCreatedAt && '' != daterangeCreatedAt) {
    queryParams.value.params["beginCreatedAt"] = daterangeCreatedAt.value[0]
    queryParams.value.params["endCreatedAt"] = daterangeCreatedAt.value[1]
  }
  if (null != daterangeUpdatedAt && '' != daterangeUpdatedAt) {
    queryParams.value.params["beginUpdatedAt"] = daterangeUpdatedAt.value[0]
    queryParams.value.params["endUpdatedAt"] = daterangeUpdatedAt.value[1]
  }
  if (null != daterangeLastUpdated && '' != daterangeLastUpdated) {
    queryParams.value.params["beginLastUpdated"] = daterangeLastUpdated.value[0]
    queryParams.value.params["endLastUpdated"] = daterangeLastUpdated.value[1]
  }
  listSysSalesInventory(queryParams.value).then(response => {
    SysSalesInventoryList.value = response.rows
    console.log("SysSalesInventoryList",response)
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    inventoryId: null,
    productId: null,
    currentQuantity: null,
    lockedQuantity: null,
    availableQuantity: null,
    createdBy: null,
    createdAt: null,
    updatedBy: null,
    updatedAt: null,
    lastUpdated: null
  }
  proxy.resetForm("SysSalesInventoryRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  daterangeCreatedAt.value = []
  daterangeUpdatedAt.value = []
  daterangeLastUpdated.value = []
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.inventoryId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加产品库存"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _inventoryId = row.inventoryId || ids.value
  getSysSalesInventory(_inventoryId).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改产品库存"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["SysSalesInventoryRef"].validate(valid => {
    if (valid) {
      if (form.value.inventoryId != null) {
        updateSysSalesInventory(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addSysSalesInventory(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _inventoryIds = row.inventoryId || ids.value
  proxy.$modal.confirm('是否确认删除产品库存编号为"' + _inventoryIds + '"的数据项？').then(function() {
    return delSysSalesInventory(_inventoryIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('SysSales/SysSalesInventory/export', {
    ...queryParams.value
  }, `SysSalesInventory_${new Date().getTime()}.xlsx`)
}

getList()
</script>
